﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using System.Xml;
using Autofac;
using Flurl.Http;
using Pay.Core;
using Pay.DTO;
using Pay.DTO.hfnative;
using Pay.DTO.hfpay;
using Pay.IService;
using Pay.Service;
using Pay.TO;

namespace Pay.Api.Controllers {
	/// <summary>
	/// 接口
	/// </summary>
	public partial class OpenController : BaseController {
		/// <summary>
		/// 网卡支付银行
		/// </summary>
		/// <param name="model"></param>
		/// <returns></returns>
		protected List<type_setting> GatewayPayBank(gateway_bank model) {
			var _iPayService = _iocContext.ResolveKeyed<IPayService>(model.pay_channel);
			return _iPayService.GatewayPayBank();
		}

		/// <summary>
		/// 发起网关支付
		/// </summary>
		/// <returns>The receive.</returns>
		/// <param name="model">Model.</param>
		protected async Task<gateway_pay_result> GatewayPay(gateway_pay_model model) {
			if (string.IsNullOrEmpty(model.order_no))
				return await ApiResultToJson.JsonAsync<gateway_pay_result>("订单号不能为空");
			else {
				if (model.order_no.Length < 13)
					return await ApiResultToJson.JsonAsync<gateway_pay_result>("订单号最小14位");
				if (model.order_no.Length > 31)
					return await ApiResultToJson.JsonAsync<gateway_pay_result>("订单号最大长度30位");
			}
			if (string.IsNullOrEmpty(model.tran_amount))
				return await ApiResultToJson.JsonAsync<gateway_pay_result>("交易金额不能为空");
			if (string.IsNullOrEmpty(model.notify))
				return await ApiResultToJson.JsonAsync<gateway_pay_result>("支付成功后服务器回调该地址不能为空");
			if (model.pay_channel == PayChannel.None)
				return await ApiResultToJson.JsonAsync<gateway_pay_result>("通道不能为空");

			var _iPayService = _iocContext.ResolveKeyed<IPayService>(model.pay_channel);
			return await _iPayService.GatewayPay(model);
		}

		/// <summary>
		/// 网关支付通知,将此url给HF
		/// </summary>
		/// <returns>The notify.</returns>
		[Route("pay/gateway_notify"), HttpPost]
		public string GatewayNotify() {
			lock (hf_gatewayLock) {
				if (HttpContext.Current.Request.InputStream.Length > 0) {
					XmlDocument xmlDoc = new XmlDocument();
					xmlDoc.Load(HttpContext.Current.Request.InputStream);
					var hfData = xmlDoc.ToObject<HFBankData<head_base, hf_gateway_notify>>();
					var _hfSign = new HfSign();
					if (_hfSign.VerifySign(hfData, hfData.head.signature)) {
						//支付成功或失败
						var order = _iChargeService.GetByTran(hfData.body.origTranId);
						try {
							if (hfData.body.tranState == "0") {
								if (order.status != ChargeStatus.Finish)
									_iChargeService.FailOrUnConfirmToSuceess(order.merchant_no, order.order_no, DateTime.Now);
							} else {
								//if (order.status == ChargeStatus.WaitPay)
								//_iChargeService.PayFail(order.merchant_no, order.order_no, hfData.body.origTranId, "支付失败");
							}
						} catch { }
						//处理平台本身的商户通知
						var setting = order.merchant.setting;
						var data = new pay_notity {
							tran_amount = (order.order_amount * 100).ToString(), order_no = order.order_no, transaction_no = order.pay_info.transaction_no,
							pay_time = order.pay_info.pay_time.HasValue ? order.pay_info.pay_time.Value : order.order_time,
							status = order.status == ChargeStatus.Finish ? 1 : 2
						};
						data.result_msg = (order.status == ChargeStatus.Finish ? "支付成功" : order.fail);
						try {
							var notify_result = order.notify.PostJsonAsync(ApiResultToJson.Json(data)).ReceiveString().Result.ToUpper();
						} catch (Exception ex) {
							var log = IocHelper.Get<ILogHelper>("info");
							log.Error("处理平台本身的商户通知：" + order.order_no);
							log.Error(ex.Message);
						}

						//回执通道
						try {
							var hfResult = new HFBankData<head_base, hf_gateway_notify_result>();
							hfResult.head = hfData.head;
							hfResult.body = new hf_gateway_notify_result { respCode = "0", respMsg = "处理完成", origTranId = hfData.body.origTranId };
							hfResult.head.signature = _hfSign.Sign(hfResult);
							return hfResult.ToXml().InnerXml;
						} catch {
							var log = IocHelper.Get<ILogHelper>("info");
							log.Error("回执有问题：" + order.order_no);
						}
					}
				}
				return "";
			}
		}

		/// <summary>
		/// 网关支付查询
		/// </summary>
		/// <returns>The pay query.</returns>
		/// <param name="model">Model.</param>
		protected async Task<pay_notity> GatewayPayQuery(refund_model_query model) {
			if (string.IsNullOrEmpty(model.order_no) && string.IsNullOrEmpty(model.transaction_no))
				return ApiResultToJson.Json<pay_notity>("查询订单号或流水号不正确");
			if (model.pay_channel == PayChannel.None)
				return await ApiResultToJson.JsonAsync<pay_notity>("通道不能为空");

			var _iPayService = _iocContext.ResolveKeyed<IPayService>(model.pay_channel);
			return await _iPayService.GatewayPayQuery(model);
		}

		/// <summary>
		/// 网关支付退款
		/// </summary>
		/// <returns>The pay refund.</returns>
		/// <param name="model">Model.</param>
		protected async Task<refund_result> GatewayPayRefund(refund_model model) {
			if (string.IsNullOrEmpty(model.tran_amount))
				return ApiResultToJson.Json<refund_result>("交易金额不能为空");
			if (string.IsNullOrEmpty(model.orig_order_no) && string.IsNullOrEmpty(model.transaction_no))
				return ApiResultToJson.Json<refund_result>("要退款的原订单号或流水号不正确");
			if (model.pay_channel == PayChannel.None)
				return ApiResultToJson.Json<refund_result>("通道不能为空");

			var _iPayService = _iocContext.ResolveKeyed<IPayService>(model.pay_channel);
			return await _iPayService.GatewayPayRefund(model);
		}

		/// <summary>
		/// 网关支付退款查询
		/// </summary>
		/// <returns>The pay refund.</returns>
		/// <param name="model">Model.</param>
		protected async Task<refund_result> GatewayPayRefundQuery(refund_model_query model) {
			if (string.IsNullOrEmpty(model.order_no) && string.IsNullOrEmpty(model.transaction_no))
				return ApiResultToJson.Json<refund_result>("查询订单号或流水号不正确");
			if (model.pay_channel == PayChannel.None)
				return ApiResultToJson.Json<refund_result>("通道不能为空");

			var _iPayService = _iocContext.ResolveKeyed<IPayService>(model.pay_channel);
			return await _iPayService.GatewayRefundQuery(model);
		}

		/// <summary>
		/// 网关支付退款通知,将此url给HF
		/// </summary>
		/// <returns>The notify.</returns>
		[Route("pay/gateway_refund_notify"), HttpPost]
		public string GatewayRefundNotify() {
			lock (hf_gatewayLock) {
				if (HttpContext.Current.Request.InputStream.Length > 0) {
					XmlDocument xmlDoc = new XmlDocument();
					xmlDoc.Load(HttpContext.Current.Request.InputStream);
					var hfData = xmlDoc.ToObject<HFBankData<head_base, hf_gateway_refund_notify>>();
					var _hfSign = new HfSign();
					if (_hfSign.VerifySign(hfData, hfData.head.signature)) {
						var order = _iRefundService.GetByTran(hfData.body.refundTranId);
						var transaction_no = hfData.body.refundTranId;
						var pay_time = DateTime.Now;
						string msg = "退款成功";
						RefundStatus status = RefundStatus.Walt;
						try {
							if (hfData.body.tranState == "0") {
								status = RefundStatus.Finish;
								if (order.status != RefundStatus.Finish)
									_iRefundService.PlatformRefundAmount(order.order_no, transaction_no, pay_time, status);
							} else if (hfData.body.tranState == "1") {
								status = RefundStatus.Walt;
								msg = "退款中";
								_iRefundService.PlatformRefundAmount(order.order_no, transaction_no, pay_time, status);
							} else {
								status = RefundStatus.Fail;
								msg = "退款失败";
								_iRefundService.PlatformRefundAmount(order.order_no, transaction_no, pay_time, status, msg);
							}
						} catch {
							msg = "退款中";
						}

						//处理平台本身的商户通知				
						//var setting = order.merchant.setting;
						//var data = new refund_result {
						//	order_no = order.order_no, transaction_no = transaction_no,
						//	pay_time = pay_time, tran_amount = (order.amount * 100).ToString(), status = status
						//};
						//var app_sortJson = SecuritySignHelper.JsonToKeyQuery2(data.ToJson());
						//var app_sign = RSAFromPkcs.sign(app_sortJson, setting.private_key, "utf-8");
						//var result_msg = new {
						//	result_code = 1000,
						//	result_msg = msg,
						//	sign = app_sign,
						//	data
						//};
						//try {
						//	var notify_result = order.notify.PostJsonAsync(result_msg).ReceiveString().Result.ToUpper();
						//	_iOrderService.AddNotifyCount(order.id, notify_result);
						//} catch (Exception ex) {
						//	var log = IocHelper.Get<ILogHelper>("info");
						//	log.Error("处理平台本身的商户通知：" + order.order_no);
						//	log.Error(ex.Message);
						//}


						//回执通道				
						try {
							var hfResult = new HFBankData<head_base, body_base>();
							hfResult.head = hfData.head;
							hfResult.body = new body_base { respCode = "0", respMsg = "处理完成" };
							hfResult.head.signature = _hfSign.Sign(hfResult);
							return hfResult.ToXml().InnerXml;
						} catch {
							var log = IocHelper.Get<ILogHelper>("info");
							log.Error("回执有问题：" + order.order_no);
						}
					}
				}
				return "";
			}
		}
	}
}
